# @author:Wei Junjie
# @time:2024/5/23 18:54
# @file jable.py
# --*--coding: gbk --*--
"""
https://jable.tv/ 爬取视频下载视频

"""
import csv
import os.path
import random
import time
import requests,re
from fake_useragent import UserAgent
from urllib import parse
from Cryptodome.Cipher import AES
import subprocess
random_header=UserAgent().random
header={"User-Agent":random_header}


# 通过关键字和页面找到数据
def search_result(keyword,page):
    keyword = parse.quote(keyword)
    while True:
        try:
            obj = requests.get('https://jable.tv/search/{}/{}/'.format(keyword,page), headers=header, timeout=15)
            if obj.status_code == 200:
                data_list = re.findall(
                """data-preview="(.*.mp4).>\s<div class="absolute-bottom-left">\s<span class="action hover-state d-none d-sm-flex" data-fav-video-id="\d+" data-fav-type="0">\s<svg height="15" width="15"><use xlink:href="#icon-heart"></use></svg>\s</span>\s</div>\s<div class="absolute-bottom-right">\s<span class="label">.*</span>\s</div>\s</a>\s</div>\s<div class="detail">\s<h6 class="title"><a href="(.*)">(.*)</a>""",obj.text)
                return data_list
            elif obj.status_code == 404:
                print('404 NOT found')
                return
            continue
        except Exception as e:
            print(e)
            time.sleep(10)
            continue

def search_m3u8(url):
    while True:
        try:
            response=requests.get(url,headers=header)
            if response.status_code==200:
                re_obj=re.compile("hlsUrl = '(.*?)'")
                m3u8_url=re_obj.search(response.text).group(1)
                return m3u8_url


                # m3u8_url_list = requests.get(m3u8_url, headers=header)
                # if m3u8_url_list.status_code == 200:
                # # 尋找片段
                #     if '#EXT-X-KEY' not in m3u8_url_list.text:
                #         pattern_ts = re.findall('\d+.ts',re.sub('#EXT.*', '', m3u8_url_list.text))
                #         return pattern_ts
                #     else:
                #         pattern_ts = re.findall('\d+.ts', re.sub('#EXT.*', '', m3u8_url_list.text))
                #         key,iv=re.compile('URI="(.*?)",IV=(.*)').findall(m3u8_url_list.text)
                #         return key,iv,m3u8_url


            continue
        except Exception as e:
            print(e)
            continue

def download_m3u8(m3u8_url):
    CMD = [r"F:\数据备份\ShareX\N_m3u8DL-CLI_v3.0.2.exe",
           m3u8_url]
    result = subprocess.run(CMD)
    if result.returncode == 0:
        print('程序运行成功')
    else:
        print('程序运行失败')


def main():
    keyword = input('请输入你要搜索的名字用繁体的形式输入:\n')
    page=input('请输入页码:\n')
    data_list=search_result(keyword,page)
    data_need_write=[]
    if data_list:
        for data in data_list:
            m3u8_url=search_m3u8(data[1])
            # download_m3u8(m3u8_url)
            data_need_write.append(data+(m3u8_url,))
            time.sleep(random.randint(3, 5))
        if keyword not in os.path.join(os.getcwd(),keyword+'.csv'):
            with open(keyword+'.csv','w',newline='') as f:
                csv_writer=csv.writer(f)
                csv_writer.writerow(['preview','video_url','title','m3u8_url'])
                csv_writer.writerows(data_need_write)
        else:
            with open(keyword+'.csv','a',newline='') as f:
                csv_writer = csv.writer(f)
                csv_writer.writerows(data_need_write)


if __name__ == '__main__':
    main()